package com.company.algo.niuke;

/**美团-二分查找
 请实现有重复数字的升序数组的二分查找
 给定一个 元素有序的（升序）整型数组 nums 和一个目标值 target  ，
 写一个函数搜索 nums 中的【第一个】出现的target，如果目标值存在返回下标，否则返回 -1
 */
public class DichotomousSearchII {
    public int search (int[] nums, int target) {
        if(nums.length <1 ) return -1;
        if(nums.length==1) return nums[0] == target ? 0: -1;
        int left = 0;
        int right = nums.length-1;
        while(left < right){
            int mid = (left + right)/2;
            if(nums[mid]==target){
                if(mid>0 && nums[mid-1]==target) {
                    right = mid;
                    continue;
                }
                return mid;
            }
            if(nums[mid] > target){
                right = mid;
            }else{
                left = mid+1;
            }
        }
        return nums[left] == target ? left: -1;
    }

    public static void main(String[] args) {
        DichotomousSearchII Main = new DichotomousSearchII();
        int[] nums = {-2,1,2};
        System.out.println(Main.search(nums, -2));
    }
}
